<template>
  <div class="demo">
    <div class="demo-title">异步加载</div>
    <div class="demo-content">
      <Mentions v-model:value="value" :loading="loading" @search="onSearch">
        <Mentions.Option v-for="{ login, avatarUrl } in users" :key="login" :value="login">
          <img :src="avatarUrl" :alt="login" style="width: 20px; margin-right: 8px" />
          <span>{{ login }}</span>
        </Mentions.Option>
      </Mentions>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { debounce } from 'lodash-es';
  import { ref } from 'vue';
  import Mentions from '@sscd/mentions';
  const value = ref<string>('');
  const loading = ref<boolean>(false);
  const users = ref<{ login: string; avatarUrl: string }[]>([]);
  const search = ref<string>('');
  const loadGithubUsers = debounce((key: string) => {
    if (!key) {
      users.value = [];
      return;
    }
    fetch(`https://api.github.com/search/users?q=${key}`)
      .then((res) => res.json())
      .then(({ items = [] }) => {
        if (search.value !== key) return;
        users.value = items.slice(0, 10);
        loading.value = false;
      });
  }, 800);
  const onSearch = (searchValue: string) => {
    search.value = searchValue;
    loading.value = !!searchValue;
    users.value = [];
    console.log('Search:', searchValue);
    loadGithubUsers(searchValue);
  };
</script>

<style lang="less" scoped></style>
